package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.entities.po.Message;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.entities.vo.MessageVO;
import com.it.schoolbookshop_back.mapper.BookMapper;
import com.it.schoolbookshop_back.mapper.MessageMapper;
import com.it.schoolbookshop_back.mapper.UserMapper;
import com.it.schoolbookshop_back.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {
    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);
    
    @Autowired
    private MessageMapper messageMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private BookMapper bookMapper;

    @Override
    public Message sendMessage(Integer senderId, Integer receiverId, Integer bookId, String content) {
        try {
            Message message = new Message();
            message.setSenderId(senderId);
            message.setReceiverId(receiverId);
            message.setBookId(bookId);
            message.setContent(content);
            message.setIsRead(false);
            
            int rows = messageMapper.insertMessage(message);
            
            // 成功保存消息后返回消息对象，包含自动生成的ID
            if (rows > 0) {
                return message;
            }
            
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Message> getChatHistory(int userId1, int userId2) {
        return messageMapper.getMessagesBetweenUsers(userId1, userId2);
    }
    
    @Override
    public List<MessageVO> getChatHistoryDetail(int userId1, int userId2, Integer currentUserId) {
        logger.info("获取聊天历史详情: userId1={}, userId2={}, currentUserId={}", userId1, userId2, currentUserId);
        
        // 获取基本聊天记录
        List<Message> messages = messageMapper.getMessagesBetweenUsers(userId1, userId2);
        
        // 查询用户信息
        User user1 = userMapper.getUserById(userId1);
        User user2 = userMapper.getUserById(userId2);
        
        if (user1 == null || user2 == null) {
            logger.error("获取用户信息失败: user1={}, user2={}", user1, user2);
            return new ArrayList<>();
        }
        
        // 转换为MessageVO列表
        List<MessageVO> messageVOs = new ArrayList<>();
        
        for (Message message : messages) {
            String senderName = message.getSenderId().equals(userId1) ? user1.getUsername() : user2.getUsername();
            String receiverName = message.getReceiverId().equals(userId1) ? user1.getUsername() : user2.getUsername();
            
            // 获取书籍标题（如果有）
            String bookTitle = null;
            if (message.getBookId() != null) {
                try {
                    bookTitle = bookMapper.getBookTitleById(message.getBookId());
                } catch (Exception e) {
                    logger.warn("获取书籍标题失败: bookId={}", message.getBookId(), e);
                }
            }
            
            MessageVO messageVO = MessageVO.fromMessage(message, senderName, receiverName, bookTitle, currentUserId);
            messageVOs.add(messageVO);
        }
        
        return messageVOs;
    }

    @Override
    public List<Map<String, Object>> getUserChatList(Integer userId) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取用户的所有聊天伙伴
        List<Integer> chatPartners = messageMapper.getUserChatPartners(userId);
        
        for (Integer partnerId : chatPartners) {
            Map<String, Object> chatInfo = new HashMap<>();
            
            // 获取聊天伙伴信息
            User partner = userMapper.getUserById(partnerId);
            if (partner != null) {
                chatInfo.put("partnerId", partnerId);
                chatInfo.put("partnerName", partner.getUsername());
                
                // 获取最后一条消息
                Message lastMessage = messageMapper.getLastMessageBetweenUsers(userId, partnerId);
                if (lastMessage != null) {
                    chatInfo.put("lastMessage", lastMessage.getContent());
                    chatInfo.put("lastMessageTime", lastMessage.getCreatedAt());
                    chatInfo.put("unreadCount", messageMapper.countUnreadMessages(partnerId, userId));
                    chatInfo.put("bookId", lastMessage.getBookId());
                }
                
                result.add(chatInfo);
            }
        }
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getUserChatListWithBookInfo(Integer userId) {
        logger.info("获取用户聊天列表（含书籍信息）: userId={}", userId);
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取用户的所有聊天伙伴
        List<Integer> chatPartners = messageMapper.getUserChatPartners(userId);
        logger.info("用户 {} 共有 {} 个聊天伙伴", userId, chatPartners.size());
        
        for (Integer partnerId : chatPartners) {
            Map<String, Object> chatInfo = new HashMap<>();
            
            // 获取聊天伙伴信息
            User partner = userMapper.getUserById(partnerId);
            if (partner != null) {
                chatInfo.put("partnerId", partnerId);
                chatInfo.put("partnerName", partner.getUsername());
                
                // 获取最后一条消息
                Message lastMessage = messageMapper.getLastMessageBetweenUsers(userId, partnerId);
                if (lastMessage != null) {
                    chatInfo.put("lastMessage", lastMessage.getContent());
                    chatInfo.put("lastMessageTime", lastMessage.getCreatedAt());
                    chatInfo.put("unreadCount", messageMapper.countUnreadMessages(partnerId, userId));
                    
                    // 存储书籍ID
                    Integer bookId = lastMessage.getBookId();
                    chatInfo.put("bookId", bookId);
                    
                    // 获取书籍标题
                    if (bookId != null) {
                        try {
                            String bookTitle = bookMapper.getBookTitleById(bookId);
                            if (bookTitle != null && !bookTitle.isEmpty()) {
                                chatInfo.put("bookTitle", bookTitle);
                                logger.info("获取到书籍标题: bookId={}, title={}", bookId, bookTitle);
                            } else {
                                chatInfo.put("bookTitle", "未知书籍");
                                logger.warn("未找到书籍标题: bookId={}", bookId);
                            }
                        } catch (Exception e) {
                            chatInfo.put("bookTitle", "未知书籍");
                            logger.error("获取书籍标题异常: bookId={}", bookId, e);
                        }
                    } else {
                        chatInfo.put("bookTitle", "无关联书籍");
                    }
                }
                
                result.add(chatInfo);
                logger.debug("添加聊天信息: partnerId={}, data={}", partnerId, chatInfo);
            }
        }
        
        logger.info("获取到 {} 条聊天记录", result.size());
        return result;
    }
    
    @Override
    public boolean markMessageAsRead(Integer messageId, Integer userId) {
        logger.info("尝试标记消息已读: messageId={}, userId={}", messageId, userId);
        
        // 先获取消息
        Message message = messageMapper.getMessageById(messageId);
        
        if (message == null) {
            logger.error("标记消息已读失败: 消息不存在, messageId={}", messageId);
            return false;
        }
        
        logger.info("获取到消息: {}, 当前用户ID: {}, 接收者ID: {}", message, userId, message.getReceiverId());
        
        // 检查当前用户是否是接收者
        if (message.getReceiverId().equals(userId)) {
            // 消息已读，无需更新
            if (Boolean.TRUE.equals(message.getIsRead())) {
                logger.info("消息已经是已读状态, messageId={}", messageId);
                return true;
            }
            
            // 更新消息状态为已读
            int rows = messageMapper.markMessageAsRead(messageId);
            logger.info("更新消息状态结果: messageId={}, 影响行数={}", messageId, rows);
            return rows > 0;
        } else {
            logger.error("标记消息已读失败: 当前用户不是接收者, userId={}, receiverId={}", userId, message.getReceiverId());
            return false;
        }
    }
    
    @Override
    public int markAllMessagesAsRead(Integer senderId, Integer currentUserId) {
        logger.info("标记所有未读消息为已读: senderId={}, currentUserId={}", senderId, currentUserId);
        
        try {
            // 确保用户存在
            User sender = userMapper.getUserById(senderId);
            User receiver = userMapper.getUserById(currentUserId);
            
            if (sender == null || receiver == null) {
                logger.error("标记所有消息已读失败: 用户不存在, senderId={}, currentUserId={}", senderId, currentUserId);
                return 0;
            }
            
            // 查找所有未读消息
            int count = messageMapper.markAllMessagesAsRead(senderId, currentUserId);
            logger.info("成功将{}条消息标记为已读", count);
            return count;
        } catch (Exception e) {
            logger.error("标记所有消息已读出错:", e);
            return 0;
        }
    }
}